class_name GameplayAbilityManager

signal ability_granted(ability_name: String)

signal ability_removed(ability_name: String)

signal ability_activated(ability_name: String, target: AbilitySystemComponent)

##
var owner: AbilitySystemComponent

##
var abilities: Array[GameplayAbility]


func _init(init_owner: AbilitySystemComponent) -> void:
    owner = init_owner


func grant_ability(ability_asset: GameplayAbilityAsset) -> void:
    # TODO: 处理重复授予能力的逻辑
    for ability: GameplayAbility in abilities:
        if ability.ability_asset.name == ability_asset.name:
            return

    var ability = ability_asset.create_spec(owner)
    abilities.append(ability)

    ability_granted.emit(ability_asset.name)


func grant_abilities(ability_assets: Array[GameplayAbilityAsset]) -> void:
    for ability_asset: GameplayAbilityAsset in ability_assets:
        grant_ability(ability_asset)


func remove_ability(ability_asset: GameplayAbilityAsset) -> void:
    for ability: GameplayAbility in abilities:
        if ability.ability_asset.name == ability_asset.name:
            abilities.erase(ability)

            ability_removed.emit(ability_asset.name)


func remove_abilities(ability_assets: Array[GameplayAbilityAsset]) -> void:
    for ability_asset: GameplayAbilityAsset in ability_assets:
        remove_ability(ability_asset)


func activate_ability(ability_name: String, target: AbilitySystemComponent) -> void:
    for ability: GameplayAbility in abilities:
        if ability.ability_asset.name == ability_name and ability.can_activate():
            ability.activate(target)

            ability_activated.emit(ability_name, target)
